<script lang="ts">
  import TodoHeader from "./components/todo-header/index.svelte"
  import TodoList from "./components/todo-list/index.svelte"
  import TodoBottom from "./components/todo-bottom/index.svelte"
  import { onMount } from "svelte"
  import type { TodoItem } from "./index.d"
  let todoList: Array<TodoItem> = []
  let isAllCheckedStatus: boolean = false

  const updateIsAllCheckedStatus = () => {
    isAllCheckedStatus = todoList.every(todo => todo.isCheck)
  }
  onMount(updateIsAllCheckedStatus)

  const addTodo = (event: CustomEvent) => {
    todoList = [
      ...todoList,
      {
        name: event.detail,
        isCheck: false,
      },
    ]
    updateIsAllCheckedStatus()
  }

  const removeTodo = (event: CustomEvent) => {
    todoList = todoList.filter((todo, index: number) => index !== event.detail)
    updateIsAllCheckedStatus()
  }

  const removeAllCheckedTodo = () => {
    todoList = todoList.filter(todo => !todo.isCheck)
  }

  const todoCheckStatusChange = () => {
    updateIsAllCheckedStatus()
  }
  const allCheckStatusChange = () => {
    isAllCheckedStatus = !isAllCheckedStatus
    todoList = todoList.map(todo => ({ name: todo.name, isCheck: isAllCheckedStatus }))
  }
</script>

<main>
  <TodoHeader on:addTodoEvent={addTodo} />
  <TodoList
    {todoList}
    on:todoCheckStatusChangeEvent={todoCheckStatusChange}
    on:removeTodoEvent={removeTodo}
  />
  {#if todoList.length}
    <TodoBottom
      {isAllCheckedStatus}
      on:allCheckStatusChangeEvent={allCheckStatusChange}
      on:removeAllCheckedTodoEvent={removeAllCheckedTodo}
    />
  {/if}
</main>

<style>
  * {
    margin: 0;
    padding: 0;
  }
</style>
